package com.tian.util;

/**
 * {@code @description:} TODO
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-04-02 21:38
 * {@code @version:} 1.0
 */
import org.redisson.Redisson;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;

import java.util.concurrent.TimeUnit;

public class SlidingWindowRateLimiter {

    private static final int MAX_PERMITS = 5;
    private static final int PERMITS_PER_SECOND = 5;

    public static void main(String[] args) throws InterruptedException {
        Config config = new Config();
        config.useSingleServer().setAddress("redis://127.0.0.1:6379");

        RedissonClient redisson = Redisson.create(config);

        RRateLimiter rateLimiter = redisson.getRateLimiter("myRateLimiter");
        rateLimiter.trySetRate(RateType.OVERALL, PERMITS_PER_SECOND, 5, RateIntervalUnit.SECONDS);

        for (int i = 0; i < 10; i++) {
            if (rateLimiter.tryAcquire()) {
                System.out.println("Access granted");
            } else {
                System.out.println("Access denied");
            }
            TimeUnit.SECONDS.sleep(1);
        }

        redisson.shutdown();
    }
}